package com.common.listener;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import javax.servlet.http.HttpSession;

public class SessionBean {
	
	private static SessionBean sessionBean;
	private Map<String,HttpSession> sessionHashMap = new HashMap<String,HttpSession>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); //线程同步
	
	//双重同步安全懒汉式
	public static SessionBean getSessionBean(){
		if(sessionBean == null){
			synchronized(SessionBean.class){
				if(sessionBean == null){
					sessionBean = new SessionBean();
				}
			}
		}
		return sessionBean;
	}
	
	//添加session
	public void addSession(String id, HttpSession httpSession) {
        readWriteLock.writeLock().lock();
        try {
            if (httpSession != null && id != null && id.length() > 0) {
                sessionHashMap.put(id, httpSession);
            }
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
 
	//删除指定session
    public void removeSession(String id) {
        readWriteLock.writeLock().lock();
        try {
            if (id != null && id.length() > 0) {
                sessionHashMap.remove(id);
            }
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
    
    //返回指定session
    public HttpSession getSession(String sessionId) {
        readWriteLock.readLock().lock();
        try {
            if (sessionId == null) {
                return null;
            }
            return sessionHashMap.get(sessionId);
        } finally {
            readWriteLock.readLock().unlock();
        }
 
    }
}
